package com.course.server;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
public class GetMethod {

    @RequestMapping(value = "/getCookies", method = RequestMethod.GET)
    public String getCookies(HttpServletResponse response) {

        Cookie cookie = new Cookie("login", "true");
        response.addCookie(cookie);

        return "成功获得cookies信息";
    }

    @RequestMapping(value = "/getWithCookies", method = RequestMethod.GET)
    public String getWithCookies(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();

        if (Objects.isNull(cookies)) {
            return "cookies为空";
        }

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("login")
                    && cookie.getValue().equals("true")) {
                return "携带cookies访问成功";
            }
        }

        return "没有对应的cookies";
    }

    @RequestMapping(value = "/getWithParam", method = RequestMethod.GET)
    public Map<String, Integer> getWithParam(@RequestParam Integer start,
                                             @RequestParam Integer end) {
        Map<String, Integer> myList = new HashMap<>();

        myList.put("苹果", 10);
        myList.put("香蕉", 7);
        myList.put("葡萄", 5);

        return myList;
    }

    @RequestMapping(value = "/getWithParam/{start}/{end}", method = RequestMethod.GET)
    public Map<String, Integer> getWithUrlParam(@PathVariable Integer start,
                                             @PathVariable Integer end) {
        Map<String, Integer> myList = new HashMap<>();

        myList.put("苹果", 10);
        myList.put("香蕉", 7);
        myList.put("葡萄", 5);

        return myList;
    }
}
